import { getHolidays } from "../services/holidays.js";
import { getFromStorage, saveToStorage } from "../storage.js";
import { translateDOM } from "../i18n.js";

function parseDate(value) {
  const d = new Date(value);
  return isNaN(d) ? null : d;
}
function formatDate(d) {
  return d.toISOString().slice(0, 10);
}

function businessDaysBetween(start, end, holidaysSet) {
  let count = 0;
  const d = new Date(start);
  while (d <= end) {
    const isWeekend = d.getDay() === 0 || d.getDay() === 6;
    const key = formatDate(d);
    if (!isWeekend && !holidaysSet.has(key)) count++;
    d.setDate(d.getDate() + 1);
  }
  return count;
}

export class DateCalculator {
  constructor(root) {
    this.root = root;
    this.render();
  }
  async render() {
    this.root.innerHTML = `
      <div class="grid">
        <label><span data-i18n="country">Country</span>
          <select id="dtCountry">
            <option value="US">US</option>
            <option value="CN">CN</option>
            <option value="GB">GB</option>
            <option value="DE">DE</option>
            <option value="JP">JP</option>
          </select>
        </label>
        <label><span data-i18n="start">Start</span><input id="dtStart" type="date" /></label>
        <label><span data-i18n="end">End</span><input id="dtEnd" type="date" /></label>
      </div>
      <div class="display" id="dtResult">0</div>
      <div class="grid" style="margin-top: 8px">
        <label><span data-i18n="reminder_title">Reminder title</span><input id="dtTitle" type="text" placeholder="Meeting" /></label>
        <label><span data-i18n="reminder_date">Reminder date</span><input id="dtReminder" type="datetime-local" /></label>
        <button class="btn" id="dtSetReminder" data-i18n="set_reminder">Set Reminder</button>
      </div>
    `;
    this.countryEl = this.root.querySelector("#dtCountry");
    this.startEl = this.root.querySelector("#dtStart");
    this.endEl = this.root.querySelector("#dtEnd");
    this.resultEl = this.root.querySelector("#dtResult");
    this.titleEl = this.root.querySelector("#dtTitle");
    this.reminderEl = this.root.querySelector("#dtReminder");
    this.btnReminder = this.root.querySelector("#dtSetReminder");

    const last = await getFromStorage("date_prefs");
    if (last) {
      this.countryEl.value = last.country || this.countryEl.value;
      if (last.start) this.startEl.value = last.start;
      if (last.end) this.endEl.value = last.end;
    }

    ["input", "change"].forEach((evt) => {
      this.countryEl.addEventListener(evt, () => this.update());
      this.startEl.addEventListener(evt, () => this.update());
      this.endEl.addEventListener(evt, () => this.update());
    });
    this.btnReminder.addEventListener("click", () => this.setReminder());
    translateDOM(this.root);
    this.update();
  }
  async update() {
    const country = this.countryEl.value;
    const start = parseDate(this.startEl.value);
    const end = parseDate(this.endEl.value);
    await saveToStorage("date_prefs", {
      country,
      start: this.startEl.value,
      end: this.endEl.value,
    });
    if (!start || !end || end < start) {
      this.resultEl.textContent = "0";
      return;
    }

    const { list } = await getHolidays(country);
    const holidaysSet = new Set(list.map((h) => h.date));
    const days = businessDaysBetween(start, end, holidaysSet);
    this.resultEl.textContent = `${days} business days`;
  }
  setReminder() {
    const title = this.titleEl.value?.trim();
    const when = this.reminderEl.value;
    if (!title || !when) return;
    const scheduleTime = new Date(when).getTime();
    chrome.runtime.sendMessage(
      {
        type: "scheduleReminder",
        when: scheduleTime,
        title,
        message: "Reminder",
      },
      () => {}
    );
  }
}
